package org.west.sky.scripture.imports.core.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Nonnull;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author chenghz
 * @date 2023/2/10 13:20
 * @description: ws消息处理器
 */
@Slf4j
@Component
public class MessageHandler extends TextWebSocketHandler {

    /**
     * 处理前端发送的文本信息
     * js调用websocket.send时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, @Nonnull TextMessage message) throws Exception {
        if (!session.isOpen()) {
            log.debug("连接已关闭，不再处理该连接的消息！");
            return;
        }
        String mes = message.getPayload();
        log.debug("收到websocket消息：{}", mes);
//        String pid = session.getAttributes().get("WEBSOCKET_PID").toString();
//        String sn = session.getAttributes().get("WEBSOCKET_SN").toString();
        if ("".equals(mes)) {
            log.debug(getSysDate() + "============接收到空消息，不予处理。");
        }
        if (mes.length() == 1) {
            //心跳消息过滤掉
            return;
        }

        log.debug(getSysDate() + "============消息处理完成：" + mes);
    }


    /**
     * 当新连接建立的时候，被调用
     * 连接成功时候，会触发页面上onOpen方法
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            //初始化连接，把session存储起来
            WebSocketManager.initUsers(session);
        } catch (Exception e) {
            log.error(getSysDate() + "============初始化连接异常-结束：" + e.getMessage(), e);
        }
    }

    /**
     * 当连接关闭时被调用
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            WebSocketManager.removeSession(session);
        } catch (Exception e) {
            log.error(getSysDate() + "============关闭连接异常-结束：" + e.getMessage(), e);
        }
    }

    /**
     * 传输错误时调用
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.debug(getSysDate() + "============发生传输错误：" + session.getId() + ";session.isOpen():" + session.isOpen() + ";exception：" + exception.getMessage());
        exception.printStackTrace();
        if (session.isOpen()) {
            //try { session.close(); } catch (Exception e) {e.printStackTrace();}
        } else {
            try {
                WebSocketManager.removeSession(session);
            } catch (Exception e) {
                log.error(getSysDate() + "============传输错误处理异常-结束：" + e.getMessage(), e);
            }
        }
    }


    private String getSysDate() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }

}
